<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="avatar" alt="" class="preview" v-if="avatar" />
      <img
        src="../../../assets/images/avatar.jpg"
        alt=""
        class="preview"
        v-else
      />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <!-- 增加文件选择框 -->
        <input
          type="file"
          accept="image/*"
          style="display: none"
          ref="iptFile"
          @change="onChangeFile"
        />
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="$refs.iptFile.click()"
          >选择图片</el-button
        >
        <el-button
          type="success"
          icon="el-icon-upload"
          :disabled="this.avatar === ''"
          @click="uploadAvatar"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data() {
    return {
      avatar: ''
    }
  },
  methods: {
    async uploadAvatar() {
      // 上传用户头像
      const { data: res } = await this.$http.patch('/my/update/avatar', {
        avatar: this.avatar
      })
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.avatar = ''
      this.$store.dispatch('user/initUserInfo')
    },
    onChangeFile(e) {
      const fileList = e.target.files
      if (fileList.length > 0) {
        //选择了图片
        console.log(fileList[0])
        //将图片转换为base64的字符串 FileReader
        const reader = new FileReader()
        // 将文件对象的数据读取到reader中,转化为base64的字符串
        reader.readAsDataURL(fileList[0])
        //load监听读取完成 reader.result
        reader.addEventListener('load', () => {
          console.log(reader.result)
          this.avatar = reader.result
        })
      } else {
        //没有选择图片
        console.log('没有选中')
        this.avatar = ''
      }
    }
    /* chooseImg() {
      // 模拟文件选择框的点击行为
      this.$refs.iptFile.click()
    } */
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>
